{-#LANGUAGE TemplateHaskell,DeriveGeneric,FlexibleInstances,QuasiQuotes,OverloadedStrings,RecordWildCards#-}
module App.Article.Model(fetchArticle,SimpleArticle(..),ArticleModel(..),fetchArticleDetail,DetailArticle(..)) where
import JavaScript.Web.XMLHttpRequest
import Data.Aeson
import Data.Int
import qualified Data.Text as T
import GHC.Generics
import Data.Monoid
import Miso.String
import Data.Maybe
import Lib.Ajax

hostAddr = "http://192.168.1.7:3000"

data ArticleModel =  ArticleModel {
   articleList::[SimpleArticle],
   showArticle::Maybe DetailArticle
} deriving (Show,Eq)

data SimpleArticle = SimpleArticle {
    id::Int64,
    title::T.Text,
    context::T.Text,
    createTime::T.Text
} deriving (Generic,Show,Eq)

instance FromJSON SimpleArticle
instance ToJSON SimpleArticle

data DetailArticle = DetailArticle {
  dId::Int64,
  dTitle::T.Text,
  dContext::T.Text,
  dCreateTime::T.Text
} deriving (Generic,Show,Eq)
instance FromJSON DetailArticle
instance ToJSON DetailArticle

fetchArticle::Int -> IO [SimpleArticle]
fetchArticle curPage = ajaxDecodeGet_ (hostAddr <> "/api/article_list/" <> show curPage)

fetchArticleDetail::Int64 -> IO DetailArticle
fetchArticleDetail idx = ajaxDecodeGet_ (hostAddr <> "/api/article/" <> show idx)